class Node {
    constructor(element) {
        this.val = element;
        this.next = null;
    }
}

class LinkedList {
    constructor(list) {
        this.first = null;
        this.size = 0;
        if (Array.isArray(list)) {
            list.forEach((val) => {
                this.add(val);
            });
        } else if (list instanceof this.constructor) {
            this.addAll(list);
        }
    }

    addAll(list) {
        var first = list.first;
        var cur = first;
        while (cur) {
            this.add(cur.val);
            cur = cur.next;
        }
    }

    add(val) {
        var node = new Node(val);
        if (!this.first) {
            this.first = node;
        } else {
            var temp = this.first;
            while (temp.next) {
                temp = temp.next;
            }
            temp.next = node;
        }
        this.size++;
    }

    removeAt(index) {
        if (index >= this.size) {
            return;
        }
        var cur = this.first; //当前元素
        var num = 0;
        var pre = null; //上一个元素
        while (cur) {
            if (num === index) {
                var next = cur.next;
                if (pre) {
                    pre.next = next;
                } else {
                    this.first = next;
                }
                this.size--;
                break;
            }
            num++;
            pre = cur;
            cur = cur.next; // 第2个
        }
    }

    removeLast() {
        this.removeAt(this.size - 1);
    }

    removeFirst() {
        this.removeAt(0);
    }

    contains(val) {
        var cur = this.first; //当前元素
        while (cur) {
            if (cur.val === val) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    get length() {
        return this.size;
    }
}

// var list = new LinkedList();
// list.add(1);
// list.add(2);
// list.add(3);
// list.add(4);

// // list.removeAt(2);
// // list.removeLast();
// // list.removeFirst();

// console.log(list)
// console.log(list.contains(5));

module.exports = {
    Node,
    LinkedList
};